<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 1/30/2015
 * Time: 11:26 AM
 */
namespace app\modules\admin\models;
use Yii;
use yii\base\Model;
class AdminLogin extends Model {
    public $username;
    public $password;
    public $_admin=false;

    public function rules(){
        return [
            [['username', 'password'], 'required'],
            ['password', 'validatePassword'],
        ];
    }

    public function validatePassword($attribute)
    {
        if (!$this->hasErrors()) {
            $user = $this->getUser();

            if (!$user || !$user->validatePassword($this->password)) {
                $this->addError($attribute, 'Incorrect username or password.');
            }
        }
    }

    public function login()
    {
        if ($this->validate()) {
            return Yii::$app->user->login($this->getUser());
        } else {
            return false;
        }
    }

    public function getUser()
    {
        if ($this->_user === false) {
            $this->_user = User::findByUsername($this->username);
        }

        return $this->_user;
    }
}